package com.tangyunlong.mall.controller;

import com.tangyunlong.mall.entity.Manager;
import com.tangyunlong.mall.service.MangerService;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;

@Slf4j
@Controller
public class ManagerController {
    @Autowired
    private MangerService mangerService;
    @GetMapping("/login")
    public String login(){
        return "login";
    }
    @PostMapping("/login")
    public String login(String account, String password, Model model, HttpSession session){
        log.debug("account:{},password:{}",account,password);
        Manager manager = mangerService.login(account, password);
        log.debug("manager:{}",manager);
        if (manager!=null){
            session.setAttribute("manager",manager);
            return "index";
        }else {
            model.addAttribute("msg","账号或密码错误");
            return "login";
        }
    }

    @GetMapping("manager/add")
    public String add(){
        return "manager_add";
    }
    @PostMapping("manager/add")
    public String add(String account, String password,Model model){
        log.debug("account:{},password:{}",account,password);
        Manager manager = new Manager();
        manager.setAccount(account);
        manager.setPassword(password);
        try {
            mangerService.add(manager);
        }catch (ArithmeticException e){
            e.printStackTrace();
            log.error("账号已存在");
            model.addAttribute("msg","账号"+account+"已存在");
            return "redirect:/manager/add";
        }
        return "redirect:/manager/list";
    }
    @GetMapping("manager/list")
    public String list(Model model){
        List<Manager> managers = mangerService.list();
        model.addAttribute("managers",managers);
        return "manager_list";
    }
    @GetMapping("manager/update/{id}")
    public String update(@PathVariable int id, Model model){
        log.debug("id:{}",id);
        Manager manager = mangerService.getById(id);
        model.addAttribute("manager",manager);
        return "manager_update";
    }
    @PostMapping("manager/update")
    public String update(Manager manager,Model model){
        log.debug("manager:{}",manager);
        try {
            mangerService.update(manager);
        }catch (ArithmeticException e){
            e.printStackTrace();
            log.error("账号已存在");
            model.addAttribute("msg","账号已存在, 请修改其他账号");
        }
        return "redirect:/manager/list";
    }
}
